<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\common\logic\SmsLogic;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\logic\PinTuanLogic;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\mall\PinTuanGoodsSkuModel;
use app\beautiful\model\mall\PinTuanGroupModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\PinTuanOrderItemModel;
use app\beautiful\model\order\PinTuanOrderModel;
use app\beautiful\model\logs\GoodsViewsModel;
use app\beautiful\model\setting\SettingSmsModel;
use think\facade\Db;

class PinTuan extends BaseController{
    public function getPinTuanGoodsList()
    {
        $today= date("Y-m-d",$this->request->time());
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['start_time','<=',$today],
            ['end_time','>=',$today],
        ];
        //获取可用的商品id集合
        $goods_where=[
            ['shop_id','=',$this->request->shopId],

            ['status','=',1],
            ['is_delete','=',0],
            ['is_open_yu','=',0],
        ];
        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];
        $where[]=['goods_id','in',$goods_ids];

        $order=['is_tui'=>'desc','fictitious_take_count'=>'desc','pin_tuan_price'=>'asc'];
        $datas=PinTuanGoodsModel::with(['goods'=>function($query){
            $query->field('goods_id,name,original_price,cover_img');
        }])->where($where)
            ->order($order)
            ->field('pin_tuan_goods_id,group_num,goods_id,pin_tuan_price,fictitious_take_count,quota')
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select()
            ->toArray();
        $return['datas']=$datas;

        return $this->success($return);

    }

    public function getPinTuanGoodsDetail()
    {
        $today= date("Y-m-d",$this->request->time());
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        //判断秒杀
        if(null === $pin_tuan_goods = PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error('拼团不存在');
        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error('拼团不存在');
        if($pin_tuan_goods->is_delete == 1) return $this->error('拼团不存在');
        if($pin_tuan_goods->status != 1) return $this->error('拼团已下架');
        if($pin_tuan_goods->start_time > $today) return $this->error('拼团还未开始');
        if($pin_tuan_goods->end_time < $today) return $this->error('拼团已结束');

        //判断秒杀商品
        if(null === $goods = GoodsModel::find($pin_tuan_goods->goods_id)) return $this->error('拼团商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('拼团商品不存在');
        if($goods->is_delete == 1) return $this->error('拼团商品不存在');
        if($goods->status != 1) return $this->error('拼团商品已下架');


        if($pin_tuan_goods->is_have_sku==1){
            $sku=PinTuanGoodsSkuModel::where([['pin_tuan_goods_id','=',$pin_tuan_goods_id],['is_delete','=',0]])
                    ->field('pin_tuan_goods_sku_id,name,original_price,pin_tuan_price,quota')
                    ->select()->toArray() ?? [];
        }

       $detail=[
            'pin_tuan_goods_id'=>$pin_tuan_goods_id,
            'goods'=>[
                'goods_id'=>$goods->goods_id,
                'rotation'=>$goods->rotation,
                'name'=>$goods->name,
                'original_price'=>$goods->original_price,
                'goods_details'=>$goods->goods_details,
                'cover_img'   => $goods->cover_img,
            ],
            'group_num'=>$pin_tuan_goods->group_num,
            'pin_tuan_price'=>$pin_tuan_goods->pin_tuan_price,
            'quota'=>$pin_tuan_goods->quota,
            'fictitious_take_count'=>$pin_tuan_goods->fictitious_take_count,
            'is_have_sku'=>$pin_tuan_goods->is_have_sku,
            'sku'=>isset($sku) ? $sku :[],
            'pin_tuan_info'=>$pin_tuan_goods->pin_tuan_info,
        ];

        $return['detail']=$detail;
        //记录拼团对应的产品访问记录
        $GoodsViewsModel = new GoodsViewsModel();
        $GoodsViewsModel->save([
            'shop_id'   => $this->request->shopId,
            'goods_id'  => $goods->goods_id
        ]);
        return $this->success($return);

    }

    //获取我的订单
    public  function getMyPintuanOrderList(){
        $where = [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId]
        ];
        $datas = PinTuanOrderModel::with(['item'])->where($where)
                ->field('pin_tuan_group_id,pin_tuan_order_id,is_chief,status,add_time,need_pay')
                ->limit($this->request->limit)
                ->page($this->request->page)
                ->order(['pin_tuan_order_id' => 'desc'])
                ->select()->append([
                    'djs_time','group_djs_time'
                ])->toArray();
        return $this->success(['list'=>$datas]);
    }
    
    public function getGroupList()
    {

        $today= date("Y-m-d",$this->request->time());
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        //判断秒杀
        if(null === $pin_tuan_goods = PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error('拼团不存在');
        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error('拼团不存在');
        if($pin_tuan_goods->is_delete == 1) return $this->error('拼团不存在');
        if($pin_tuan_goods->status != 1) return $this->error('拼团已下架');
        if($pin_tuan_goods->start_time > $today) return $this->error('拼团还未开始');
        if($pin_tuan_goods->end_time < $today) return $this->error('拼团已结束');

        //判断秒杀商品
        if(null === $goods = GoodsModel::find($pin_tuan_goods->goods_id)) return $this->error('拼团商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('拼团商品不存在');
        if($goods->is_delete == 1) return $this->error('拼团商品不存在');
        if($goods->status != 1) return $this->error('拼团商品已下架');

        $group=PinTuanGroupModel::with(['chief'=>function($query){
            $query->field('member_id,nick_name,face');
               
        }])->where([
            ['shop_id','=',$this->request->shopId],
            ['pin_tuan_goods_id','=',$pin_tuan_goods->pin_tuan_goods_id],
            ['status','=',1],
            ['add_time','>=',$this->request->time()-86400]
        ])->field('pin_tuan_group_id,chief_id,pin_tuan_goods_id,add_time,group_size,num') 
            ->append(['djs_time','remain_num'])
            ->limit(5)
            ->select()->toArray();

        return $this->success(['datas'=>$group]);
    }

    public function createOrder()
    {
        $logistics_type=$this->request->param('logistics_type/d');
        $receiving_name=$this->request->param('receiving_name');
        $receiving_mobile=$this->request->param('receiving_mobile');
        $pin_tuan_group_id=$this->request->param('pin_tuan_group_id/d',0);
        $receiving_address_province=$this->request->param('receiving_address_province');
        $receiving_address_city=$this->request->param('receiving_address_city');
        $receiving_address_county=$this->request->param('receiving_address_county');
        $receiving_address_info=$this->request->param('receiving_address_info');
        $total_price = $this->request->param('total_price/f',0);
        $use_integral = $this->request->param('use_integral/d',0);
        $coupon_id = $this->request->param('coupon_id/d',0);
        $goods=$this->request->param('goods/a',[]);
        $params=[
            'member_id'=>$this->request->memberId,
            'logistics_type'=>$logistics_type,
            'receiving_name'=>$receiving_name,
            'receiving_mobile'=>$receiving_mobile,
            'receiving_address_province'=>$receiving_address_province,
            'receiving_address_city'=>$receiving_address_city,
            'receiving_address_county'=>$receiving_address_county,
            'receiving_address_info'=>$receiving_address_info,
            'total_price'=>$total_price,
            'use_integral'=>$use_integral,
            'coupon_id'=>$coupon_id,
            'goods'=>$goods,
            'pin_tuan_group_id'=>$pin_tuan_group_id,
        ];
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_id=$order_logic['pin_tuan']->createOrder($params);
            Db::commit();
            return $this->success(['order_id'=>$order_id]);
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }


    }

    public function cancelPay()
    {
        $order_id=$this->request->param('order_id/d',0);
        $params=[
            'order_id'=>$order_id,
            'member_id'=>$this->request->memberId,
        ];
        Db::startTrans();
        try{
            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);
            $pin_tuan_logic->cancelPay($params);
            Db::commit();
            return $this->success('取消拼团成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function moneyPay()
    {
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = PinTuanOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 900;//订单15分钟
        if($order->add_time < $time){ //如果 订单超过15分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        Db::startTrans();
        try{
            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->use_integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $res = $MemberWalletLogic->useBalance($needPay, $order->total_price + $order->freight , 8); //商城购物使用
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->status = 2;
            $order->pay_type = 'money';
            $order->save();

            //支付成功后的
            $params=[
                'order_id'=>$order->pin_tuan_order_id,
                'member_id'=>$this->request->memberId,
            ];
            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);
            $pin_tuan_logic->payOk($params);

            //发送短信给管理员
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->order_notice_admin==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'money'=>$needPay,
                        ];
                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');
                    }
                }
            }catch (\Exception $e){

            }
            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function cancelPinTuan()
    {
        $order_id = $this->request->param('order_id/d',0);
        $params=[
            'order_id'=>$order_id,
            'member_id'=>$this->request->memberId,
        ];
        Db::startTrans();
        try{
            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);
            $pin_tuan_logic->cancelPinTuan($params);
            Db::commit();
            return $this->success('取消成功');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function getPinTuanDetail()
    {
        $pin_tuan_order_id=$this->request->param('pin_tuan_order_id/d',0);
        if($pin_tuan_order_id==0) return $this->error('拼团不存在');

        //判断拼团订单存不存在
        if(null === $pin_tuan_order = PinTuanOrderModel::find($pin_tuan_order_id)){
            return $this->error('拼团不存在');
        }
        if($pin_tuan_order->shop_id != $this->request->shopId)  return $this->error('拼团不存在');
        if($pin_tuan_order->member_id != $this->request->memberId) return $this->error('拼团不存在');

        //如果已经参团了，判断团队存不存在
        if($pin_tuan_order->pin_tuan_group_id !=0 ){
            if(null === $pin_tuan_group = PinTuanGroupModel::find($pin_tuan_order->pin_tuan_group_id)){
                return $this->error('拼团不存在');
            }
        }

        //判断拼团订单商品存不存在
        if(null === $pin_tuan_order_item = PinTuanOrderItemModel::where('pin_tuan_order_id',$pin_tuan_order_id)->find()){
            return $this->error('拼团不存在');
        }

        $goods_info=[
            'goods_name'=>$pin_tuan_order_item->goods_name,
            'goods_cover_img'=>$pin_tuan_order_item->goods_cover_img,
            'goods_sku_id'  => $pin_tuan_order_item->goods_sku_id,
            'goods_sku_name'=>$pin_tuan_order_item->goods_sku_name,
            'goods_original_price'=>$pin_tuan_order_item->goods_original_price,
            'goods_price'=>$pin_tuan_order_item->goods_price,
            'group_size'=>$pin_tuan_order_item->group_size,
        ];
       
        $members=PinTuanOrderModel::where([
          ['shop_id','=',$this->request->shopId],
          ['pin_tuan_group_id','=',$pin_tuan_order->pin_tuan_group_id],
          ['status','in',[2,3,-1,-2]],
          ['is_paid','=',1]
      ])->field('member_id,member_face,member_name,is_chief')->order(['is_chief'=>'desc'])
          ->select()->toArray();
        
        $return=[
            'pin_tuan_order_id' => $pin_tuan_order_id,
            'pin_tuan_group_id'=>$pin_tuan_order->pin_tuan_group_id,
            'status'=>$pin_tuan_order->status,
            'status_means'=>$pin_tuan_order->status_means,
            'goods_info'=>$goods_info,
            'djs_time' => $pin_tuan_order->djs_time,
            'need_pay' => $pin_tuan_order->need_pay, 
            'group_djs_time' => $pin_tuan_order->group_djs_time,
            'members'=>$members
        ];

        if($pin_tuan_order->pin_tuan_group_id !=0 ){
            $djs_time=$pin_tuan_group->add_time + 86400 - time();
            $group=[
                'remain_num'=>$pin_tuan_group->group_size - $pin_tuan_group->num,
                'djs_time'=>$djs_time > 0 ? $djs_time : 0
            ];
            $return['group']=$group;
        }

        return $this->success($return);
    }

    public function showPinTuanDetail()
    {
        $pin_tuan_group_id=$this->request->param('pin_tuan_group_id/d',0);
        if($pin_tuan_group_id==0) return $this->error('拼团不存在');

        //判断团队
        if(null === $pin_tuan_group = PinTuanGroupModel::find($pin_tuan_group_id)){
            return $this->error('拼团不存在');
        }
        if($pin_tuan_group->shop_id != $this->request->shopId) return $this->error('拼团不存在');
        if($pin_tuan_group->add_time + 86400 - time() <0) return $this->error('拼团时间已过');
        $djs_time=$pin_tuan_group->add_time + 86400 - time();
        $group=[
            'remain_num'=>$pin_tuan_group->group_size - $pin_tuan_group->num,
            'djs_time'  =>$djs_time > 0 ? $djs_time : 0,
            'status'    => $pin_tuan_group->status,
            'group_size'=>$pin_tuan_group->group_size,
            'num'       => $pin_tuan_group->num,
        ];
        //判断拼团商品
        $pin_tuan_goods=PinTuanGoodsModel::where([
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['pin_tuan_goods_id','=',$pin_tuan_group->pin_tuan_goods_id],
        ])->field('pin_tuan_goods_id,goods_id,pin_tuan_price,quota,take_count,fictitious_take_count,is_have_sku,group_num')
            ->find();
        if(null === $pin_tuan_goods) return $this->error('拼团商品不存在');

        $goods=GoodsModel::find($pin_tuan_goods->goods_id);
        empty($goods) && $this->error('商品不存在');
        $pin_tuan_goods->toArray();
        $pin_tuan_goods['goods'] = $goods->toArray();
        if($pin_tuan_goods['is_have_sku']==1){
            $sku=PinTuanGoodsSkuModel::where([
                ['shop_id','=',$this->request->shopId],
                ['pin_tuan_goods_id','=',$pin_tuan_goods->pin_tuan_goods_id],
                ['quota','>',0],
                ['is_delete','=',0]
            ])->select()->toArray();
            $pin_tuan_goods['sku']=$sku;
        }

        //获取参团人员
        $members=PinTuanOrderModel::where([
            ['shop_id','=',$this->request->shopId],
            ['pin_tuan_group_id','=',$pin_tuan_group_id],
            ['status','IN',[2,3,-1,-2]],
            ['is_paid','=',1]
        ])->field('member_id,member_face,member_name,is_chief')->order(['is_chief'=>'desc'])
            ->select()->toArray();
        
         
        $return=[
            'goods'=>$pin_tuan_goods,
            'group'=>$group,
            'members'=>$members
        ];
        $return['group']=$group;
        $return['pmember'] = null;
        //判断邀请人
        $member_id = $this->request->param('member_id/d',0);
        if(!empty($member_id)){
            if(null === $pmember = MemberModel::find($member_id)) return $this->error('邀请人不存在');
            if($pmember->shop_id != $this->request->shopId) return $this->error('邀请人不存在');
            $return['pmember'] = [
                'member_id'=>$pmember->member_id,
                'nick_name'=>$pmember->nick_name,
                'face'=>$pmember->face,
            ];
        }
      
       
        return $this->success($return);

    }

}
